package com.app.Controller;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.UserDataHandler;

import com.app.Activity.frmNhomChoActivity;
import com.app.Activity.frmTreeNodeActivity;
import com.app.DTO.RoleDTO;
import com.app.PhanQuyen.Quyen;
import com.app.Tree.TreeNode;
//import com.app.TreeNode.TreeNode;

import ReadWriteXML.CMember;
import ReadWriteXML.CNeighbor;
import ReadWriteXML.DOMUltil;
import ReadWriteXML.ReadXML;
import ReadWriteXML.WriteXML;
import android.R.integer;
import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class ReadWriteFileController {
	final private static String SEPARATOR = "/";
	final private static String SEPARATOR1 = "##";
	private static String _fNameListGroup = "ListGroupJoin.txt";
	public static String DIRECTORY = Environment.getExternalStorageDirectory().toString() + "/";
	public static String DIRECTORYMES = DIRECTORY + "MES/";
	public static String DIRECTORYCHAT = DIRECTORY + "MES/CHAT/";
	public static String DIRECTORYCHATPEER = DIRECTORY + "MES/CHAT/PEER/";
	public static String DIRECTORYCHATGROUP = DIRECTORY + "MES/CHAT/GROUP/";
	public static String DIRECTORYTEST = DIRECTORY + "MES/TEST/";
	public static String DIRECTORYTESTCONTENT = DIRECTORY + "MES/TEST/CONTENT/";

	public static String pathNeighborsList = DIRECTORY + "NeighborsList.xml";

	public static String RULE_BASE_PATH = "ListRule.xml";
	public static String MY_ROLE_PATH = DIRECTORY + "myRole.xml";
	public static String ROLE_SETTING_PATH = DIRECTORY + "mySettingRole.xml";
	public static String ROLE_DEFAULT_PATH = DIRECTORY + "roleMacDinh.xml";
	public static String MEMBER_PATH = DIRECTORY + "memberList.xml";
	public static String TREE_PATH = DIRECTORY + "tree.xml";
	public static String RATING_PATH = DIRECTORY + "ratingList.xml";
	public static String DeletedNodesPath = DIRECTORY + "DeletedNodes.xml";
	
	//public static String LOG_PATH = DIRECTORY + tenNhom +"LogList.xml";
	
	public static boolean deleteFile(String path) {
		File f1 = new File(path);
		boolean success = f1.delete();
		if (!success) {
			System.out.println("Deletion failed.");
		} else {
			System.out.println("File deleted.");
		}
		return success;
	}

	public static boolean isFile(String path) {
		File f = new File(path);
		return f.exists();
	}

	/**
	 * Phú Đọc danh sách Quyền từ file
	 * 
	 * @param path
	 *            : Đường dẫn tới file
	 * @return ArrayList<Quyen>
	 */

	public static ArrayList<Quyen> readRule(Context context,String path) {
		ArrayList<Quyen> rs = null;

		//Document doc = ReadXML.BuildXML(path);
		Document doc=ReadXML.buildFromAsset(context, path);

		if (doc != null) {
			rs = new ArrayList<Quyen>();
			NodeList nodeList = doc.getElementsByTagName("Rule");
			int n = nodeList.getLength();
			for (int i = 0; i < n; i++) {
				Element e = (Element) nodeList.item(i);

				boolean read = Boolean.parseBoolean(e.getElementsByTagName("read").item(0).getChildNodes().item(0)
						.getNodeValue());

				boolean write = Boolean.parseBoolean(e.getElementsByTagName("write").item(0).getChildNodes().item(0)
						.getNodeValue());
				boolean send = Boolean.parseBoolean(e.getElementsByTagName("send").item(0).getChildNodes().item(0)
						.getNodeValue());
				boolean receive = Boolean.parseBoolean(e.getElementsByTagName("receive").item(0).getChildNodes()
						.item(0).getNodeValue());

				Quyen quyen = new Quyen(read, write, send, receive, e.getAttribute("ID"), e.getAttribute("Name"));
				rs.add(quyen);

			}
		}

		return rs;
	}

	/**
	 * Phú Đọc danh sách vai trò từ file
	 * 
	 * @param path
	 *            : Đường dẫn tới file
	 *	@param context
	 *			: nếu bằng NULL thì đọc ở file bình thường, khác NULL thì đọc trong thư mục assets
	 * 
	 * @return ArrayList<RoleDTO>
	 */

	public static ArrayList<RoleDTO> readRole(Context context,String path) {
		ArrayList<RoleDTO> rs = new ArrayList<RoleDTO>();
		
		Document doc ;//= ReadXML.BuildXML(path);
		if(context==null){
			doc = ReadXML.BuildXML(path);
		}else{
			doc=ReadXML.buildFromAsset(context, "roleMacDinh.xml");
		}
		if (doc != null) {

			rs = new ArrayList<RoleDTO>();
			NodeList roleList = doc.getElementsByTagName("Role");
			if (roleList == null || roleList.getLength() == 0) {
				Log.i("Phu","không có file: "+path);
				return rs;
			}
			int n = roleList.getLength();

			for (int i = 0; i < n; i++) {
				Element element = (Element) roleList.item(i);
				RoleDTO role = new RoleDTO();
				role.setName(element.getAttribute("Name"));

				NodeList ruleList = element.getElementsByTagName("Rule");

				int m = ruleList.getLength();

				for (int j = 0; j < m; j++) {
					Element e = (Element) ruleList.item(j);

					boolean read = Boolean.parseBoolean(e.getElementsByTagName("read").item(0).getChildNodes().item(0)
							.getNodeValue());

					boolean write = Boolean.parseBoolean(e.getElementsByTagName("write").item(0).getChildNodes()
							.item(0).getNodeValue());
					boolean send = Boolean.parseBoolean(e.getElementsByTagName("send").item(0).getChildNodes().item(0)
							.getNodeValue());
					boolean receive = Boolean.parseBoolean(e.getElementsByTagName("receive").item(0).getChildNodes()
							.item(0).getNodeValue());

					Quyen rule = new Quyen(read, write, send, receive, e.getAttribute("ID"), e.getAttribute("Name"));
					role.addRule(rule);

				}
				rs.add(role);
			}
		}		
		return rs;
	}

	/**
	 * Phú Tạo node XML từ 1 quyền
	 * 
	 * @param doc
	 *            : Document
	 * @param rule
	 *            : Quyền
	 * @return Node
	 */
	private static Node createRuleNode(Document doc, Quyen rule) {

		Element e = doc.createElement("Rule");
		e.setAttribute("ID", rule.getID());
		e.setAttribute("Name", rule.getName());

		Node read = doc.createElement("read");
		Node write = doc.createElement("write");
		Node send = doc.createElement("send");
		Node receive = doc.createElement("receive");

		read.setTextContent(rule.getRead().toString());
		write.setTextContent(rule.getWrite().toString());
		send.setTextContent(rule.getSend().toString());
		receive.setTextContent(rule.getReceive().toString());

		e.appendChild(read);
		e.appendChild(write);
		e.appendChild(send);
		e.appendChild(receive);

		return (Node) e;
	}

	/**
	 * Tạo Node XML từ 1 RoleDTO (Vai trò)
	 * 
	 * @param doc
	 *            :Document
	 * @param role
	 *            :Vai trò
	 * @return Node
	 */
	private static Node createRoleNode(Document doc, RoleDTO role) {
		Element e = doc.createElement("Role");
		e.setAttribute("ID", role.getName());
		e.setAttribute("Name", role.getName());
		int n = role.getRuleList().size();

		for (int i = 0; i < n; i++) {
			e.appendChild(createRuleNode(doc, role.getRuleList().get(i)));
		}
		return (Node) e;

	}

	/**
	 * Phú Ghi danh sách Vai trò (RoleDTO) xuống file XML
	 * 
	 * @param path
	 *            : Đường dẫn
	 * @param roleList
	 *            : Danh sách vai trò
	 */
	public static void writeRole(String path, ArrayList<RoleDTO> roleList) {
		if (isFile(path))
			deleteFile(path);
		Document doc = null;
		doc = WriteXML.insertRoot(doc, path, "RoleList");

		Log.d("Phu", "root =null" + (doc.getFirstChild() == null));
		for (int i = 0; i < roleList.size(); i++) {
			doc.getFirstChild().appendChild(createRoleNode(doc, roleList.get(i)));
		}
		DOMUltil.writeXmlToFile(path, doc);
		if (isFile(path))
			Log.d("Phu", "writeRole nội dung ptử 0(parse): " + roleList.get(0).toParse());
		else
			Log.d("Phu", "chua ghi" + path);
	}

	/**
	 * Insert 1 vai trò vào 1 file XML có sẵn. Nếu file ko tồn tại thì tạo file
	 * mới
	 * 
	 * @param path
	 *            : Đường dẫn
	 * @param role
	 *            : Vai trò
	 */
	public static void insertRole(String path, RoleDTO role) {
		if (isFile(path)) {
			Document doc = ReadXML.BuildXML(path);
			doc.getFirstChild().appendChild(createRoleNode(doc, role));
			DOMUltil.writeXmlToFile(path, doc);
		} else {
			ArrayList<RoleDTO> roleList = new ArrayList<RoleDTO>();
			roleList.add(role);
			writeRole(path, roleList);
		}
	}

	/**
	 * Phú Cập nhật 1 vai trò trong 1 file xml có sẵn (dựa vào tên vai trò)
	 * 
	 * @param path
	 *            : Đường dẫn
	 * @param oldRole
	 *            : Vai trò cần cập nhật
	 * @param newRole
	 *            : Vai trò mới
	 */
	public static void updateRole(String path, RoleDTO oldRole, RoleDTO newRole) {		
		Document doc = null;
		doc = DOMUltil.parse(path);		
		NodeList listRole = doc.getElementsByTagName("Role");

		int n = listRole.getLength();
		for (int i = 0; i < n; i++) {
			Element e = (Element) listRole.item(i);
			if (e.getAttribute("Name").equals(oldRole.getName())) {
				e.getParentNode().removeChild(e);
				doc.getFirstChild().appendChild(createRoleNode(doc, newRole));
				break;
			}
		}
		DOMUltil.writeXmlToFile(path, doc);
	}

	/**
	 * Xóa 1 Vai trò trong 1 file XML
	 * 
	 * @param path
	 *            : Đường dẫn
	 * @param role
	 *            : Vai trò cần xóa
	 */
	public static void deleteRole(String path, RoleDTO role) {

		Document doc = null;
		doc = DOMUltil.parse(path);
		NodeList listRole = doc.getElementsByTagName("Role");
		int n = listRole.getLength();
		for (int i = 0; i < n; i++) {
			Element e = (Element) listRole.item(i);
			if (e.getAttribute("Name").equals(role.getName())) {
				e.getParentNode().removeChild(e);
				break;
			}
		}
		DOMUltil.writeXmlToFile(path, doc);
	}

	public static ArrayList<CNeighbor> readNeighbor() {
		ArrayList<CNeighbor> listNeighbor = new ArrayList<CNeighbor>();
		ArrayList<CMember> listMember = new ArrayList<CMember>();
		Document _doc = ReadXML.BuildXML(ReadWriteFileController.pathNeighborsList);
		Log.d("PEERDROID", "pathNeighborsList: " + ReadWriteFileController.pathNeighborsList);
		listMember = ReadXML.ReadMember(_doc);
		boolean temp = false;

		for (int i = 0; i < listMember.size(); i++) {
			CMember mem = new CMember();
			mem = listMember.get(i);
			CNeighbor neighbor = new CNeighbor(mem, temp);
			listNeighbor.add(neighbor);
		}
		return listNeighbor;

	}

	public static ArrayList<CMember> readMember(String path) {
		return ReadXML.ReadMember(path);
	}

	/**
	 * Phú Ghi danh sách thành viên xuống file
	 * 
	 * @param path
	 * @param memberList
	 */
	public static void writeMember(String path, ArrayList<CMember> memberList) {
		
		Document doc = null;
		doc = WriteXML.insertRoot(doc, path, "ListLearner");
		Log.d("Phu","writeMember xuống file xml");
		for (int i = 0; i < memberList.size(); i++) {
			doc.getFirstChild().appendChild(createMemberNode(doc, memberList.get(i)));
		}
		DOMUltil.writeXmlToFile(path, doc);
	}

	/**
	 * Phú Insert 1 member xuống file.(Nếu file ko tồn tại thì tạo mới) Nếu
	 * member đã tồn tại thì ko insert
	 * 
	 * @param path
	 * @param member
	 */
	public static void insertMember(String path, CMember member) {		
		if (isFile(path)) {
			ArrayList<CMember> memberList = readMember(path);
			for (CMember m : memberList) {
				if (m.get_userName().equals(member.get_userName()))
					return;
			}
			Document doc = ReadXML.BuildXML(path);
			doc.getFirstChild().appendChild(createMemberNode(doc, member));
			DOMUltil.writeXmlToFile(path, doc);
		} else {
			ArrayList<CMember> memberList = new ArrayList<CMember>();
			memberList.add(member);
			writeMember(path, memberList);
		}
	}

	/**
	 * Phú Xóa 1 member trong file XML dựa vào user name
	 * 
	 * @param path
	 * @param member
	 */
	public static void deleteMember(String path, CMember member) {
		Document doc = null;
		doc = DOMUltil.parse(path);
		NodeList listMember = doc.getElementsByTagName("ListLearner");
		int n = listMember.getLength();
		for (int i = 0; i < n; i++) {
			Element e = (Element) listMember.item(i);
			if (e.getAttribute("UserName").equals(member.get_userName())) {
				e.getParentNode().removeChild(e);
				break;
			}
		}
		DOMUltil.writeXmlToFile(path, doc);
	}

	private static Node createMemberNode(Document doc, CMember member) {
		Element e = doc.createElement("Learner");
		e.setAttribute("UserName", member.get_userName());

		Node ip = doc.createElement("IP");
		Node fullName = doc.createElement("FullName");

		ip.setTextContent(member.get_ip());
		fullName.setTextContent(member.get_fullName());

		e.appendChild(ip);
		e.appendChild(fullName);

		return (Node) e;
	}

	// chat rieng
	public static boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}

		// The directory is now empty so delete it
		return dir.delete();
	}

	public static boolean deleteFolder(String path) {
		File f1 = new File(path);
		boolean success = deleteDir(f1);
		if (!success) {
			System.out.println("Deletion failed.");
		} else {
			System.out.println("File deleted.");
		}
		return success;
	}

	public static void writeTXT(String fileName, String content) throws IOException {
		File file = new File(DIRECTORY + fileName);
		boolean exist = file.createNewFile();
		if (!exist) {
			FileWriter fstream = new FileWriter(file, true);
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(content + "\r\n");
			out.close();
		} else {
			FileWriter fstream = new FileWriter(file, true);
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(content + "\r\n");
			out.close();
			Log.d("PEERDROID", "Da tao file thanh cong");
		}
	}

	public static ArrayList<String> ReadTXT(String path) {
		ArrayList<String> arrMessage = new ArrayList<String>();
		try {
			// Open the file that is the first
			// command line parameter
			if (isFile(path)) {
				FileInputStream fstream = new FileInputStream(path);
				// Get the object of DataInputStream
				DataInputStream in = new DataInputStream(fstream);
				BufferedReader br = new BufferedReader(new InputStreamReader(in));
				String strLine;
				// Read File Line By Line
				while ((strLine = br.readLine()) != null) {
					// Print the content on the console
					arrMessage.add(strLine);
				}
				// Close the input stream
				in.close();
			}
		} catch (Exception e) {// Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}
		return arrMessage;
	}

	public static void writeTXTPath(String path, String content) throws IOException {
		File file = new File(path);
		boolean exist = file.createNewFile();
		if (!exist) {
			FileWriter fstream = new FileWriter(file, true);
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(content + "\r\n");
			out.close();
		} else {
			FileWriter fstream = new FileWriter(file, true);
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(content + "\r\n");
			out.close();
			Log.d("PEERDROID", "Da tao file thanh cong");
		}
	}

	// end chat rieng

	// Ghi tree node
//	public static void writeTree(ArrayList<TreeNode> treeNodeList) {
//		String path=TREE_PATH;
//		if (isFile(path)) {
//			deleteFile(path);
//		}
//		Document doc = null;
//		doc = WriteXML.insertRoot(doc, path, "ListLearner");
//
//		for (TreeNode node : treeNodeList) {
//			Log.d("Phu", node.getId()+": "+(node.getParentNode() == null ? "-1" : node.getParentNode().getId() + ""));
//			Element e = doc.createElement("Node");
//			e.setAttribute("id", node.getId() + "");
//			e.setAttribute("x", node.getX() + "");
//			e.setAttribute("y", node.getY() + "");
//			e.setAttribute("text", node.getText());
//			e.setAttribute("parentID", (node.getParentNode() == null ? "-1" : node.getParentNode().getId() + ""));
//			e.setAttribute("user", node.getUser());
//			doc.getFirstChild().appendChild(e);
//		}
//		DOMUltil.writeXmlToFile(path, doc);
//	}
//
//	//Insert node
//	public static void insertTreeNode(TreeNode node){
//		String path=TREE_PATH;
//		if (isFile(path)) {
//			
//			Document doc = ReadXML.BuildXML(path);
//			Element e=doc.createElement("Node");
//			e.setAttribute("id", node.getId() + "");
//			e.setAttribute("x", node.getX() + "");
//			e.setAttribute("y", node.getY() + "");
//			e.setAttribute("text", node.getText());
//			e.setAttribute("parentID", (node.getParentNode() == null ? "-1" : node.getParentNode().getId() + ""));
//			e.setAttribute("user", node.getUser());
//			doc.getFirstChild().appendChild(e);
//			DOMUltil.writeXmlToFile(path, doc);
//		} else {
//			TreeNode nodeRoot = new TreeNode(null, "Node gốc", 0, "");
//			ArrayList<TreeNode> treeNodeList = new ArrayList<TreeNode>();
//			treeNodeList.add(nodeRoot);
//			treeNodeList.add(node);
//			writeTree(treeNodeList);
//		}
//	}
//	public static ArrayList<TreeNode> readTree() {
//		String path=TREE_PATH;
//		ArrayList<TreeNode> rs = new ArrayList<TreeNode>();
//		Document doc = ReadXML.BuildXML(path);
//		if (doc != null) {
//			NodeList nodeList = doc.getElementsByTagName("Node");
//			int n = nodeList.getLength();
//			for (int i = 0; i < n; i++) {
//				Element e = (Element) nodeList.item(i);
//				String text = e.getAttribute("text");
//				float x = Float.parseFloat(e.getAttribute("x"));
//				float y = Float.parseFloat(e.getAttribute("y"));
//				int parentID = Integer.parseInt(e.getAttribute("parentID"));
//				TreeNode parentNode= new TreeNode(null, null, parentID, null);
//				int id = Integer.parseInt(e.getAttribute("id"));
//				String user = e.getAttribute("user");
//				TreeNode treeNode = new TreeNode(null, text, x, y, parentNode, id, user);
//				rs.add(treeNode);
//				Log.d("Phu","read: "+id+" "+parentID);
//			}
//		}
//		return rs;
//	}
//	
	
	
	/** An
	 *  Ghi danh sách Đánh giá xuống file XML
	 * 
	 * @param path
	 *            : Đường dẫn
	 * @param rating
	 *            : Danh sách Đánh giá
	 */
	public static void writeRating(String path, ArrayList<ArrayList<String>> rating, int count) {
		if (isFile(path))
			deleteFile(path);
		Document doc = null;
		doc = WriteXML.insertRoot(doc, path, "RatingList");

		Log.d("Phu", "root =null" + (doc.getFirstChild() == null));
		for (int i = 0; i < rating.size(); i++) {
			doc.getFirstChild().appendChild(createRatingNode(doc, rating.get(i), count));
		}
		DOMUltil.writeXmlToFile(path, doc);
		if (isFile(path))
			Log.d("Phu", "writeRating nội dung ptử 0(parse): " );
		else
			Log.d("Phu", "chua ghi" + path);
	}
	
	/**An
	 * Tạo Node XML từ 1 ratinglist 
	 * 
	 * @param doc
	 *            :Document
	 * @param ratinglist
	 *            
	 * @return Node
	 */
	private static Node createRatingNode(Document doc, ArrayList<String> ratinglist, int count) {
		Element e = doc.createElement("Rating");
		Log.d("Phu", "Name" + ratinglist.get(0));
		e.setAttribute("Name", ratinglist.get(0));
		float d = Float.parseFloat(ratinglist.get(1));
		float kq = (d*20)/count;
		e.setAttribute("Point", String.valueOf(kq)+" %");
		
		return (Node) e;
	}
	
	/** An
	 * Insert 1 Log vào 1 file XML có sẵn. Nếu file ko tồn tại thì tạo file
	 * mới
	 * 
	 * @param path
	 *            : Đường dẫn
	 * @param role
	 *            : Log
	 */
	public static void insertLogFile(String path, String text, String userName) {
		if (isFile(path)) {
			Document doc = ReadXML.BuildXML(path);
			doc.getFirstChild().appendChild(createLogNode(doc, text,userName));
			DOMUltil.writeXmlToFile(path, doc);
		} else {
			
			writeLogFile(path, text,userName);
		}
	}
	
	/** An
	 *  Ghi Log xuống file XML
	 * 
	 * @param path
	 *            : Đường dẫn
	 * @param 
	 *            : Danh sách hoạt động
	 */
	public static void writeLogFile(String path, String text, String userName) {
		if (isFile(path))
			deleteFile(path);
		Document doc = null;
		
		doc = WriteXML.insertRoot(doc, path, "LogFile");
		Log.d("Phu", "da tao được Root " );
		doc.getFirstChild().appendChild(createLogNode(doc,text,userName));
		
		DOMUltil.writeXmlToFile(path, doc);
		if (isFile(path))
			Log.d("Phu", "writeRating nội dung ptử 0(parse): " );
		else
			Log.d("Phu", "chua ghi" + path);
	}
	/**An
	 * Tạo Node XML  
	 * 
	 * @param doc
	 *            :Document
	 *
	 *            
	 * @return Node
	 */
	private static Node createLogNode(Document doc, String text, String username) {

        String sDate = getDateTime();
        Log.d("Phu", "Datetime " + sDate);
		Element e = doc.createElement("Action");
		Log.d("Phu", "Name: " + username);
		Log.d("Phu", "da tao được Element " );
		e.setAttribute("on","("+ sDate + ") "+username+ ": " +text);	
		Log.d("Phu", "da tao được Attribute " );
		return (Node) e;
	}
	
	/**An
	 * Lấy thời gian 
	 * 
	 * @param 
	 *            
	 *            
	 * @return String
	 */
	public static String getDateTime(){
		Calendar c = Calendar.getInstance();//Lấy ngày tháng hiện tại
        SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy/HH:mm:ss"); // thiết lập kiểu hiễn thị ngày giờ
        String sDate = df.format(c.getTimeInMillis());// Lấy giờ hiện tại
        Log.d("Phu", "Datetime " + sDate);
		
		/*Calendar c = Calendar.getInstance();
        int month=c.get(Calendar.MONTH)+1;
        String sDate = c.get(Calendar.YEAR) + "-" + month+ "-" + c.get(Calendar.DAY_OF_MONTH) +
        "|" + c.get(Calendar.HOUR_OF_DAY)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND);
        Log.d("Phu", "Datetime " + sDate);*/
        return sDate;
	}
	/**An
	 * Kiểm tra trước khi ghi file 
	 * 
	 * @param 
	 *            
	 *            
	 * @return String
	 */
	public static void checkRuleWriteToLogFile(String text){
		Log.d("Phu", "đã vào checkIsThanhLapNhom: " + text);
		if(NetworkController._peer.account.isThanhLapNhom != true){
			ArrayList<CMember> cmem = ReadWriteFileController.readMember(ReadWriteFileController.MEMBER_PATH);
	        for(int i=0; i<cmem.size(); i++){
	        	
	        	Log.d("Phu","Text: " +text);
	        	String name = NetworkController._peer.getAccount().get_Username();
	        	NetworkController.sendTextLog(cmem.get(i).get_ip(), text, name);
	        }
	        WriteToLogFile(text);
		}else{
			WriteToLogFile(text);
		}
	}
	/**An
	 * Ghi xuống Log file 
	 * 
	 * @param 
	 *            
	 *            
	 * @return String
	 */
	public static void WriteToLogFile(String text){
		
		Log.d("Phu","WriteToLogFile "+ NetworkController._peer.getAccount().get_Username() + "-"+ text );
        String username = NetworkController._peer.getAccount().get_Username();
        String tenNhom = NetworkController.getGroupName();
		String path = ReadWriteFileController.DIRECTORY + tenNhom+"LogList.xml";
        ReadWriteFileController.insertLogFile(path, text, username);
	}
	/**An
	 * đọc file Log 
	 * 
	 * @param 
	 *            
	 *            
	 * @return String
	 */
	public static ArrayList<String> readLogFile(Context context,String path) {
		ArrayList<String> rs = new ArrayList<String>();
	
		Document doc = ReadXML.BuildXML(path);
		if (doc != null) {

			rs = new ArrayList<String>();
			NodeList action = doc.getElementsByTagName("Action");
			int n = action.getLength();
			if(n!= 0)
			{
				for(int i=0; i<n; i++)
				{
					Element e = (Element)action.item(i);
					rs.add(e.getAttribute("on"));
				}
			}
		}
		return rs;
	}
	
	public static void deleteTreeNodes(String []idArray){
		String path=TREE_PATH;
		Document doc = null;
		if(doc==null)
			return;
		doc = DOMUltil.parse(path);
		NodeList list = doc.getElementsByTagName("Node");
		int n = list.getLength();
		for(int i=0;i<idArray.length;i++){
			for (int j = 0; j < n; j++) {
				Element e = (Element) list.item(j);
				if (e.getAttribute("id").equals(idArray[i])) {
					e.getParentNode().removeChild(e);
					break;
				}
			}
		}
		DOMUltil.writeXmlToFile(path, doc);
	}
	public static void updateTreeNodeText(String text, int id){
		Log.d("Phu","RW Controller updateTreeNodeText "+id+" "+text);
		String path=TREE_PATH;
		Document doc = null;
		doc = DOMUltil.parse(path);		
		if(doc==null)
			return;
		NodeList listRole = doc.getElementsByTagName("Node");

		int n = listRole.getLength();
		for (int i = 0; i < n; i++) {
			Element e = (Element) listRole.item(i);
			if (e.getAttribute("id").equals(id+"")) {
				
				Element e1=doc.createElement("Node");
				e1.setAttribute("id", id + "");
				e1.setAttribute("x", e.getAttribute("x"));
				e1.setAttribute("y", e.getAttribute("y"));
				e1.setAttribute("text", text);
				e1.setAttribute("parentID", e.getAttribute("parentID"));
				e1.setAttribute("user", e.getAttribute("user"));
				
				
				e.getParentNode().removeChild(e);
				Log.d("An","da cap nhat node:"+e1.getAttribute("text"));
				doc.getFirstChild().appendChild(e1);
				break;
			}
		}
		DOMUltil.writeXmlToFile(path, doc);
	}
	public static String readTreeText() {		
		StringBuilder builder=new StringBuilder();
		try {
			BufferedReader buff=new BufferedReader(new FileReader(TREE_PATH));
			String line;
			while((line=buff.readLine())!=null){
				builder.append(line);
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return builder.toString();
	}
	public static void writeTreeText(String data){
		deleteFile(TREE_PATH);
		try {
			BufferedWriter  writer=new BufferedWriter(new FileWriter(TREE_PATH));
			writer.write(data);
			writer.flush();
			Log.d("Phu","writeTreeText: data="+data);
		} catch (Exception e) {
			Log.d("Phu", "Lỗi trong hàm: writeTreeText "+e.getMessage());
		}
		Log.d("Phu","writeTreeText: "+TREE_PATH);
	}
	
	public static long getVersionTree(){
		long vs = 0;
		Document doc = ReadXML.BuildXML(TREE_PATH);
		Element e = (Element) doc.getFirstChild().getFirstChild();
		vs = Long.parseLong(e.getAttribute("version"));
		Log.d("An", "ReadWriteFileController-getVersionTree in XML: " + vs);
		return vs;
	}
	public static void writeFile(String path, String data){
		try {
			BufferedWriter  writer=new BufferedWriter(new FileWriter(path));
			writer.write(data);
			writer.flush();
			Log.d("Phu","writeFile: data="+data);
		} catch (Exception e) {
			Log.d("Phu", "Lỗi trong hàm: writeFile "+e.getMessage());
		}
	}
}


